package org.algorithm.二师兄.数组.二月;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * good luck guys
 * keep learing for algorithm
 *
 */
public class 两数之和 {

    public static void main(String[] args) {
        int[] arr = {3,8,5,0,9,2,1};
        int target = 10;
        int[] twoSum = twoSum(arr, target);
        System.out.println(Arrays.toString(twoSum));
    }

    /***
     *  两树之和
     */
    private static int[] twoSum(int[] arr, int target){
        if (arr == null || arr.length == 0) return arr;
        // 1. HashMap 题解
        Map<Integer, Integer> hashMap = new HashMap<>(2);
        for (int i = 0; i < arr.length; i++) {
            if (hashMap.containsKey(target - arr[i])) {
                return new int[]{hashMap.get(target - arr[i]), i};
            }else {
                hashMap.put(arr[i], i);
            }
        }

        // 2. 双指针
        Arrays.sort(arr);
        int left = 0;
        int right = arr.length - 1;
        while (left != right) {
            if (arr[left] + arr[right] > target) {
                right--;
            }else if (arr[left] + arr[right] < target) {
                left++;
            }else {
                return new int[]{left, right};
            }
        }
        return null;
    }


}
